package Serialize;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class StudentListApplication 
{
	
	public void buildStudentList(StudentList list)
	{
		String[] students = {"Shi Ren", "Xiaoshuang", "Da xiong", "Huahua", "Yongwei", "Mu Hua"};
		for(int i=0; i<students.length; i++)
			list.addStudent(students[i]);
	}
	
	public void putStudentList(StudentList list)
	{
		try 
		{
			ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("repple.txt"));
			os.writeObject(list);
			os.flush();
			os.close();
			
		} catch (FileNotFoundException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			
		} catch (IOException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			
		}
		
	}
	
	public StudentList getStudentList()
	{
		StudentList list = null;
		
		try 
		{
			ObjectInputStream is = new ObjectInputStream(new FileInputStream("repple.txt"));
			list = (StudentList)is.readObject();
			is.close();
		} 
		catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (FileNotFoundException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
				
		return list;
	}
	
	public void invoke()
	{
		StudentList list = new StudentList();
		buildStudentList(list);
		
		System.out.println("Before serialized:");
		list.listStudents();
		
		putStudentList(list);
		System.out.println("After serialized:");
		StudentList afterList = getStudentList();
		afterList.listStudents();
	}
	
	public static void main(String args[])
	{
		StudentListApplication app = new StudentListApplication();
		app.invoke();
	}
}
